package com.yxq.mdt.app.modules.video.ui.fragment;


import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.animation.OvershootInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.yxq.mdt.app.R;
import com.yxq.mdt.app.base.BaseFragment;
import com.yxq.mdt.app.modules.message.ui.MessageTabActivity;
import com.yxq.mdt.app.modules.search.ui.SearchCommunityActivity;
import com.yxq.mdt.app.modules.socialcontact.adapter.ExamplePagerAdapter;
import com.yxq.mdt.app.modules.video.bean.AdvertBean;
import com.yxq.mdt.app.modules.video.bean.ChannelListBean;
import com.yxq.mdt.app.modules.video.bean.MLUserList;
import com.yxq.mdt.app.modules.video.model.MainVideoModel;
import com.yxq.mdt.app.modules.video.presenter.IMainVideoContract;
import com.yxq.mdt.app.modules.video.presenter.MainVideoPresenter;
import com.yxq.mdt.app.utils.ScaleTransitionPagerTitleView;
import com.yxq.mdt.app.widgets.ViewPagerFixed;

import net.lucode.hackware.magicindicator.FragmentContainerHelper;
import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.buildins.UIUtil;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.SimplePagerTitleView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author L
 * @time 2019-12-09
 * @describe 密聊
 */
public class MainVideoFragment extends BaseFragment<MainVideoPresenter> implements IMainVideoContract.View {
    @BindView(R.id.video_magic_indicator)
    MagicIndicator videoMagicIndicator;
    @BindView(R.id.video_view_pager)
    ViewPagerFixed videoViewPager;
    private static final String[] CHANNELS = new String[]{"蜜聊", "附近"};
    @BindView(R.id.main_video_iv_msg)
    ImageView mainVideoIvMsg;
    @BindView(R.id.main_video_iv_search)
    ImageView mainVideoIvSearch;
    private List<String> mDataList = Arrays.asList(CHANNELS);
    private List<Fragment> mFragments = new ArrayList<Fragment>();
    private ExamplePagerAdapter mExamplePagerAdapter;
    private FragmentContainerHelper mFragmentContainerHelper = new FragmentContainerHelper();
    MainVideoChatFragment videoChatFragment;
    VideoNearbyFragment videoNearbyFragment;

    @Override
    protected int attachLayoutId() {
        return R.layout.fragment_main_video;
    }

    @Override
    protected MainVideoPresenter getPresenter() {
        return new MainVideoPresenter(this, new MainVideoModel());
    }

    @Override
    public void initView(View view) {
        initFragments();
        mExamplePagerAdapter = new ExamplePagerAdapter(getChildFragmentManager(), mFragments, mDataList);
        videoViewPager.setAdapter(mExamplePagerAdapter);
        initMagicIndicator4();
        mFragmentContainerHelper.handlePageSelected(0, false);
    }

    @Override
    public void initData() {
        cameraPermissionCheck();
    }

    /**
     * 滑动页面至顶部并刷新数据
     */
    public void refresh() {
        if (videoChatFragment != null) {
            videoChatFragment.refresh();
        }
        if (videoNearbyFragment != null) {
            videoNearbyFragment.refresh();
        }
    }

    private void initMagicIndicator4() {
        CommonNavigator commonNavigator = new CommonNavigator(mContext);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {
            @Override
            public int getCount() {
                return mDataList.size();
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {
                SimplePagerTitleView simplePagerTitleView = new ScaleTransitionPagerTitleView(context); //使用自定义
                simplePagerTitleView.setNormalColor(Color.BLACK);
                simplePagerTitleView.setSelectedColor(Color.BLACK);
                simplePagerTitleView.setText(mDataList.get(index));
                simplePagerTitleView.setTextSize(20);
                simplePagerTitleView.setOnClickListener(v -> {
                    videoViewPager.setCurrentItem(index);
                });
                return simplePagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator linePagerIndicator = new LinePagerIndicator(context);
                linePagerIndicator.setMode(LinePagerIndicator.MODE_EXACTLY);
                linePagerIndicator.setLineWidth(UIUtil.dip2px(context, 40));
                linePagerIndicator.setLineHeight(UIUtil.dip2px(context, 2));
                linePagerIndicator.setColors(Color.parseColor("#FFD800"));
                return linePagerIndicator;
            }
        });
        videoMagicIndicator.setNavigator(commonNavigator);
        LinearLayout titleContainer = commonNavigator.getTitleContainer(); // must after setNavigator
        titleContainer.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE);
        titleContainer.setDividerDrawable(new ColorDrawable() {
            @Override
            public int getIntrinsicWidth() {
                return UIUtil.dip2px(mContext, 0);
            }
        });
        final FragmentContainerHelper fragmentContainerHelper = new FragmentContainerHelper(videoMagicIndicator);
        fragmentContainerHelper.setInterpolator(new OvershootInterpolator(0.1f));
        fragmentContainerHelper.setDuration(0);
        videoViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                fragmentContainerHelper.handlePageSelected(position);
                if (1 == position) {
                    //判断定位权限
                    locationPermissionCheck();
                } else {
                    cameraPermissionCheck();
                }
            }
        });
        videoViewPager.setOffscreenPageLimit(2);
    }

    /**
     * 获取权限
     */
    private void cameraPermissionCheck() {
        if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(mContext, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            //申请相机，麦克风权限
            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA}, 10010);
        }
    }

    /**
     * 获取定位权限
     */
    private void locationPermissionCheck() {
        if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            //申请定位权限
            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 10086);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //可在此继续其他操作。
//        videoNearbyFragment.refresh();
    }

    //初始化fragment addFragment
    private void initFragments() {

        //密聊
        videoChatFragment = new MainVideoChatFragment();
        Bundle videoChatFragmentBundle = new Bundle();
        videoChatFragmentBundle.putString(MainVideoChatFragment.EXTRA_TEXT, CHANNELS[0]);
        videoChatFragment.setArguments(videoChatFragmentBundle);
        mFragments.add(videoChatFragment);

        //附近
        videoNearbyFragment = new VideoNearbyFragment();
        Bundle videoNearbyFragmentBundle = new Bundle();
        videoNearbyFragmentBundle.putString(VideoNearbyFragment.EXTRA_TEXT, CHANNELS[1]);
        videoNearbyFragment.setArguments(videoNearbyFragmentBundle);
        mFragments.add(videoNearbyFragment);

    }

    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public void onChannelListSuccess(List<ChannelListBean> channelListBeanList) {

    }

    @Override
    public void onChannelListFailed(String error) {

    }

    @Override
    public void onUserListSuccess(MLUserList userList) {

    }

    @Override
    public void onUserListFailed(String error) {

    }

    @Override
    public void onAdvertSuccess(AdvertBean advertBean) {

    }

    @Override
    public void onAdvertSuccessFailed(String error) {

    }

    @OnClick({R.id.main_video_iv_msg, R.id.main_video_iv_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.main_video_iv_msg:
                //消息
                Intent intent = new Intent(mContext, MessageTabActivity.class);
                startActivity(intent);
                break;
            case R.id.main_video_iv_search:
                //搜索
                intent = new Intent(mContext, SearchCommunityActivity.class);
                startActivity(intent);
                break;
        }
    }
}